package io.netty.example.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2023/3/7
 * @description:
 */
public class NettyServer {

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ChannelInitializer<SocketChannel> myInitializer = new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                System.out.println("childHandler my ChannelInitializer-initChannel...");
                p.addLast(new SimpleInboundHandler("SimpleInboundHandlerA",false));
                p.addLast(new SimpleInboundHandler("SimpleInboundHandlerB",false));
                p.addLast(new SimpleInboundHandler("SimpleInboundHandlerC",true));

                p.addLast(new SimpleOutboundHandler("SimpleOutboundHandlerA"));
                p.addLast(new SimpleOutboundHandler("SimpleOutboundHandlerB"));
                p.addLast(new SimpleOutboundHandler("SimpleOutboundHandlerC"));

            }
        };

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    //.handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(myInitializer);

            // Start the server.
            ChannelFuture f = b.bind(9000).sync();
            System.out.println("NettyServer started...");

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } catch (Exception ex){
            ex.printStackTrace();
        }finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }


    public static class SimpleInboundHandler extends ChannelInboundHandlerAdapter {
        private String name;
        private boolean reply;

        public SimpleInboundHandler(String name, boolean reply) {
            this.name = name;
            this.reply = reply;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("InboundHandler: "+name);
            if(reply){
                ctx.channel().writeAndFlush(msg);
            }else {
                //throw new RuntimeException("InboundHandler: "+name);
                ctx.fireChannelRead(msg);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("InBoundHandlerException Caught: "+name);
            ctx.fireExceptionCaught(cause);
        }
    }

    public static class SimpleOutboundHandler extends ChannelOutboundHandlerAdapter{
        private String name;
        public SimpleOutboundHandler(String name) {
            this.name = name;
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            System.out.println("OutboundHandler: "+ name);
            if("SimpleOutboundHandlerB".equals(name)){
                throw new RuntimeException("OutboundHandler: "+name);
            }else {
                super.write(ctx, msg, promise);
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("OutBoundHandlerException Caught:"+name);
            super.exceptionCaught(ctx, cause);
        }
    }



}
